<template>
    <div idm-ctrl="idm_module" :id="moduleObject.id" :idm-ctrl-id="moduleObject.id" class="IDataList_app scrollbar_style">
        <div class="header row flex_between">
            <div v-for="(item) in header_list" :key="item.key" class="cell" :style="getCellStyle(item)">{{ item.label }}</div>
        </div>
        <div class="main scrollbar_style">
            <van-list v-if="data_list && data_list.length" :offset="propData.offset" :immediate-check="false" v-model="loading" :finished="finished" :loading-text="propData.loadingText" :finished-text="propData.finishedText" @load="onLoad" >
                <div v-for="(item,index) in data_list" :key="index" class="row flex_between">
                    <div v-for="(item1) in header_list" :key="item1.key" class="cell" :style="getCellStyle(item1)">{{ item[item1.key] }}</div>
                </div>
            </van-list>
            <div v-else class="empty_block flex_column_center">
                <SvgIcon icon-class="empty"></SvgIcon>
                <div class="text">暂无数据</div>
            </div>
        </div>
    </div>
</template>
  
<script>
import { getHeaderListDataMock,getListDataMock } from '../mock/mockData';
import SvgIcon from '../icons/SvgIcon.vue';

export default {
    name: 'IDataList',
    components: {
        SvgIcon
    },
    data() {
        return {
            moduleObject: {},
            propData: this.$root.propData.compositeAttr || {
                headerList: [ ],
                size: 10,
                finishedText: '没有更多了',
                loadingText: '加载中...'
            },
            header_list: [],
            data_list: [],
            page: 1,
            loading: false,
            finished: false,
            parentHeight: '',
            conditionObject: {},
        }
    },
    props: {
    },
    watch: {
        
    },
    created() {
        this.moduleObject = this.$root.moduleObject;
        this.convertAttrToStyleObject();
        this.getHeaderList()
        this.initData(1)
    },
    mounted() {
        this.$nextTick(function (params) {

        });
    },
    destroyed() { },
    methods: {
        getHeaderList() {
            if ( this.propData.headerList && this.propData.headerList.length ) {
                this.header_list = JSON.parse(JSON.stringify(this.propData.headerList));
            } else {
                this.header_list = getHeaderListDataMock()
            }
        }, 
        getCellStyle(item) {
            let styleObject = {};
            if ( item.width ) {
                styleObject['width'] = item.width;
                styleObject['flex-shrink'] = 0;
            }
            if ( item.textAlign ) {
                styleObject['text-align'] = item.textAlign;
            }
            return styleObject
        },
        onLoad() {
            console.log('触发加载-size',this.page);
            this.page = this.page + 1;
            if ( this.page == 1 ) {
                this.loading = false;
                return
            }
            this.initData()
        },
        makeParamsData(data) {
            let result = {};
            if ( this.propData.paramsMakeFunction && this.propData.paramsMakeFunction.length && window[this.propData.paramsMakeFunction[0].name] ) {
                result = window[this.propData.paramsMakeFunction[0].name].call(this, {
                                        ...data,
                                        ...this.propData.paramsMakeFunction[0].param,
                                        moduleObject: this.moduleObject,
                                        _this: this
                                    });
                console.log('自定义参数函数',result)
                return result
            }
            return data
        },
        initData(is_init) {
            if ( is_init ) {
                this.page = 1;
                this.data_list = [];
            }
            this.finished = false;
            let that = this;
            let param = {
                [that.propData.sizeKey]: that.propData.size,
                [that.propData.pageKey]: that.page,
                ...this.conditionObject
            }
            if ( this.propData.selectRuleId ) {
                param['selectRuleId'] = this.propData.selectRuleId
            }
            param = this.makeParamsData(param)
            if ( that.propData.dataSource && that.propData.dataSource.length ) {
                IDM.datasource.request(that.propData.dataSource[0].id,{
                    moduleObject:that.moduleObject,
                    param: param
                },function(res){
                    if ( that.page == 1 ) {
                        that.data_list = res;
                    } else {
                        that.data_list.push(...res);
                    }
                    that.loading = false;
                    if ( res && res.length < that.propData.size ) {
                        that.finished = true;
                    }
                },function(error){
                    //这里是请求失败的返回结果
                })
            } else {
                that.data_list = getListDataMock()
                that.loading = false;
                that.finished = true;
            }
        },
        
        /**
         * 提供父级组件调用的刷新prop数据组件
         */
        propDataWatchHandle(propData) {
            this.propData = propData.compositeAttr || {};
            this.convertAttrToStyleObject();
            this.initData(1)
        },
        convertThemeListAttrToStyleObject() {
            const themeList = this.propData.themeList;
            if ( (!themeList) || !themeList.length ) {
                return
            }
            const themeNamePrefix = IDM.setting && IDM.setting.applications && IDM.setting.applications.themeNamePrefix ? IDM.setting.applications.themeNamePrefix : "idm-theme-";
            for (var i = 0; i < themeList.length; i++) {
                var item = themeList[i];
                
                if(item.key!=IDM.theme.getCurrentThemeInfo()){
                    //此处比对是不渲染输出不用的样式，如果页面会刷新就可以把此处放开
                    continue;
                }
                let borderObject = {
                    'border-color': item.mainColor ? item.mainColor.hex8 : "",
                }
                IDM.setStyleToPageHead( "." + themeNamePrefix + item.key + " #" + (this.moduleObject.packageid || "module_demo") + " .ant-select-selection:hover", borderObject );
                IDM.setStyleToPageHead( "." + themeNamePrefix + item.key + " #" + (this.moduleObject.packageid || "module_demo") + " .ant-select-focused .ant-select-selection, .ant-select-selection:focus, .ant-select-selection:active", borderObject );
            }
        },
        /** * 把属性转换成样式对象 */
        convertAttrToStyleObjectHeader() {
            var styleObject = {};
            for (const key in this.propData) {
                if (this.propData.hasOwnProperty.call(this.propData, key)) {
                    const element = this.propData[key];
                    if (!element && element !== false && element != 0) {
                        continue;
                    }
                    switch (key) {
                        case "heightHeader":
                            styleObject['height'] = element;
                            break;
                        case "bgColorHeader":
                            if (element && element.hex8) {
                                styleObject["background-color"] = element.hex8;
                            }
                            break;
                        case "fontHeader":
                            IDM.style.setFontStyle(styleObject,element)
                            break;
                    }
                }
            }
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .header', styleObject);
        },
        convertAttrToStyleObjectMain() {
            var styleObject = {};
            var styleObjectItem = {};
            var styleObjectStripe = {};
            var styleObjectFinished = {};
            var styleObjectLoading = {};
            var styleObjectEmptyText = {};
            var styleObjectEmptyIcon = {};
            if ( this.propData.stripe && this.propData.bgColorStripe && this.propData.bgColorStripe.hex8 ) {
                styleObjectStripe["background-color"] = this.propData.bgColorStripe.hex8;
            }
            for (const key in this.propData) {
                if (this.propData.hasOwnProperty.call(this.propData, key)) {
                    const element = this.propData[key];
                    if (!element && element !== false && element != 0) {
                        continue;
                    }
                    switch (key) {
                        case "heightMainItem":
                            styleObjectItem['height'] = element;
                            break;
                        case "heightMain":
                            styleObject['height'] = element;
                            break;
                        case "bgColorMain":
                            if (element && element.hex8) {
                                styleObject["background-color"] = element.hex8;
                            }
                            break;
                        case "fontMain":
                            IDM.style.setFontStyle(styleObject,element)
                            break;
                        case "fontFinished":
                            IDM.style.setFontStyle(styleObjectFinished,element)
                            break;
                        case "fontLoading":
                            IDM.style.setFontStyle(styleObjectLoading,element)
                            break;
                        case "fontEmptyText":
                            IDM.style.setFontStyle(styleObjectEmptyText,element)
                            break;
                        case "fontEmptyIcon":
                            IDM.style.setFontStyle(styleObjectEmptyIcon,element)
                            break;
                        case "boxEmptyIcon":
                            IDM.style.setBoxStyle(styleObjectEmptyIcon,element)
                    }
                }
            }
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .row:nth-child(even)', styleObjectStripe);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main', styleObject);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .row', styleObjectItem);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .van-list__finished-text', styleObjectFinished);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .van-loading__spinner', styleObjectLoading);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .van-loading__text', styleObjectLoading);

            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .empty_block .svg-icon', styleObjectEmptyIcon);
            window.IDM.setStyleToPageHead(this.moduleObject.id + ' .main .empty_block .text', styleObjectEmptyText);
        },
        convertAttrToStyleObject() {
            this.convertAttrToStyleObjectHeader()
            this.convertAttrToStyleObjectMain()
            var styleObject = {};
            if (this.propData.bgSize && this.propData.bgSize == "custom") {
                styleObject["background-size"] = (this.propData.bgSizeWidth ? this.propData.bgSizeWidth.inputVal + this.propData.bgSizeWidth.selectVal : "auto") + " " + (this.propData.bgSizeHeight ? this.propData.bgSizeHeight.inputVal + this.propData.bgSizeHeight.selectVal : "auto")
            } else if (this.propData.bgSize) {
                styleObject["background-size"] = this.propData.bgSize;
            }
            if (this.propData.positionX && this.propData.positionX.inputVal) {
                styleObject["background-position-x"] = this.propData.positionX.inputVal + this.propData.positionX.selectVal;
            }
            if (this.propData.positionY && this.propData.positionY.inputVal) {
                styleObject["background-position-y"] = this.propData.positionY.inputVal + this.propData.positionY.selectVal;
            }
            for (const key in this.propData) {
                if (this.propData.hasOwnProperty.call(this.propData, key)) {
                    const element = this.propData[key];
                    if (!element && element !== false && element != 0) {
                        continue;
                    }
                    switch (key) {
                        case "width":
                            styleObject[key] = element;
                            break;
                        case "height":
                            if ( (element == 'auto' || element == '') && this.parentHeight ) {
                                styleObject[key] = this.parentHeight + 'px';
                            } else {
                                styleObject[key] = element;
                            }
                            break;
                        case "bgColor":
                            if (element && element.hex8) {
                                styleObject["background-color"] = element.hex8;
                            }
                            break;
                        case "box":
                            IDM.style.setBoxStyle(styleObject,element)
                            break;
                        case "bgImgUrl":
                            styleObject["background-image"] = `url(${window.IDM.url.getWebPath(element)})`;
                            break;
                        case "positionX":
                            //背景横向偏移

                            break;
                        case "positionY":
                            //背景纵向偏移

                            break;
                        case "bgRepeat":
                            //平铺模式
                            styleObject["background-repeat"] = element;
                            break;
                        case "bgAttachment":
                            //背景模式
                            styleObject["background-attachment"] = element;
                            break;
                        case "border":
                            IDM.style.setBorderStyle(styleObject,element)
                            break;
                        case "font":
                            IDM.style.setFontStyle(styleObject,element)
                            break;
                    }
                }
            }
            window.IDM.setStyleToPageHead(this.moduleObject.id, styleObject);
        },
        /**
         * 通用的url参数对象
         * 所有地址的url参数转换
         */
        commonParam() {
            let urlObject = IDM.url.queryObject();
            var params = {
                pageId:
                    window.IDM.broadcast && window.IDM.broadcast.pageModule
                        ? window.IDM.broadcast.pageModule.id
                        : "",
                urlData: JSON.stringify(urlObject),
            };
            return params;
        },
        
        /** * 通用的获取表达式匹配后的结果 */
        getExpressData(dataName, dataFiled, resultData) {
            //给defaultValue设置dataFiled的值
            var _defaultVal = undefined;
            if (dataFiled) {
                var filedExp = dataFiled;
                filedExp =
                    dataName +
                    (filedExp.startsWiths("[") ? "" : ".") +
                    filedExp;
                var dataObject = { IDM: window.IDM };
                dataObject[dataName] = resultData;
                _defaultVal = window.IDM.express.replace.call(
                    this,
                    "@[" + filedExp + "]",
                    dataObject
                );
            }
            //对结果进行再次函数自定义
            if (this.propData.customFunction && this.propData.customFunction.length > 0) {
                var params = this.commonParam();
                var resValue = "";
                try {
                    resValue = window[this.propData.customFunction[0].name] && window[this.propData.customFunction[0].name].call(this, {
                        ...params,
                        ...this.propData.customFunction[0].param,
                        moduleObject: this.moduleObject,
                        expressData: _defaultVal, interfaceData: resultData
                    });
                } catch (error) {
                }
                _defaultVal = resValue;
            }

            return _defaultVal;
        },
        /**
         * 组件通信：接收消息的方法
         * @param {
         *  type:"发送消息的时候定义的类型，这里可以自己用来要具体做什么，统一规定的type：linkageResult（组件联动传结果值）、linkageDemand（组件联动传需求值）、linkageReload（联动组件重新加载）
         * 、linkageOpenDialog（打开弹窗）、linkageCloseDialog（关闭弹窗）、linkageShowModule（显示组件）、linkageHideModule（隐藏组件）、linkageResetDefaultValue（重置默认值）"
         *  message:{发送的时候传输的消息对象数据}
         *  messageKey:"消息数据的key值，代表数据类型是什么，常用于表单交互上，比如通过这个key判断是什么数据"
         *  isAcross:如果为true则代表发送来源是其他页面的组件，默认为false
         * } object 
         */
         onReInitDataMsgKey(conditionObject,messageKey){
            this.conditionObject = {
                ...this.conditionObject,
                ...conditionObject
            };
            this.initData(1)
        },
        receiveBroadcastMessage(object) {
            console.log("组件收到消息", object)
            if( object.type && object.type=="linkageReload" ){
                this.initData(1);
            }
            if (object && object.type == "regionResize" && object.message && object.message.gridEleTarget) {
                let gridEleTarget = object.message.gridEleTarget;
                if (gridEleTarget && gridEleTarget.offsetHeight) {
                    this.parentHeight = gridEleTarget.offsetHeight;
                    this.$nextTick(() => {
                        if ( this.propData.height == 'auto' && gridEleTarget.offsetHeight ) {
                            this.convertAttrToStyleObject()
                        } 
                    })
                }
            }
            if(object.type&&object.type=="linkageDemand"){
                if(object.messageKey){
                    this.onReInitDataMsgKey(object.message,object.messageKey);
                }
            }
        },
        /**
         * 组件通信：发送消息的方法
         * @param {
         *  type:"自己定义的，统一规定的type：linkageResult（组件联动传结果值）、linkageDemand（组件联动传需求值）、linkageReload（联动组件重新加载）
         * 、linkageOpenDialog（打开弹窗）、linkageCloseDialog（关闭弹窗）、linkageShowModule（显示组件）、linkageHideModule（隐藏组件）、linkageResetDefaultValue（重置默认值）",
         *  message:{实际的消息对象},
         *  rangeModule:"为空发送给全部，根据配置的属性中设定的值（值的内容是组件的packageid数组），不取子表的，比如直接 this.$root.propData.compositeAttr["attrKey"]（注意attrKey是属性中定义的bindKey）,这里的格式为：['1','2']"",
         *  className:"指定的组件类型，比如只给待办组件发送，然后再去过滤上面的值"
         *  globalSend:如果为true则全站发送消息，注意全站rangeModule是无效的，只有className才有效，默认为false
         * } object 
         */
        sendBroadcastMessage(object) {
            window.IDM.broadcast && window.IDM.broadcast.send(object);
        },
        /**
         * 交互功能：设置组件的上下文内容值
         * @param {
         *  type:"定义的类型，已知类型：pageCommonInterface（页面统一接口返回值）、"
         *  key:"数据key标识，页面每个接口设置的数据集名称，方便识别获取自己需要的数据"
         *  data:"数据集，内容为：字符串 or 数组 or 对象"
         * }
         */
        setContextValue(object) {
            console.log("统一接口设置的值", object);
            if (object.type != "pageCommonInterface") {
                return;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.IDataList_app{
    height: 100%;
    overflow: auto;
    .header{
        height: 50px;
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #C1C1C1;
        letter-spacing: 0;
        font-weight: 400;
        background: #0641AD;
    }
    .row{
        height: 50px;
        .cell{
            flex-shrink: 1;
            width: 100%;
        }
    }
    .main{
        height: calc(100% - 50px);
        overflow: auto;
        .empty_block{
            height: 100%;
            text-align: center;
            .svg-icon{
                margin-bottom: 10px;
                font-size: 90px;
                color: #666666ff;
            }
            .text{
                font-size: 14px;
                color: #666666ff;
            }
        }
    }
}
</style>
<style lang="scss">
.scrollbar_style::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}
.scrollbar_style::-webkit-scrollbar-thumb {
    background-color: #ccc;
}
.scrollbar_style::-webkit-scrollbar-thumb {
    min-height: 18px;
    border-radius: 4px;
}

.IDataList_app{
    .van-list{
        height: 100%;
    }
}

</style>
